package common

import (
	"encoding/json"
	"io/ioutil"
	"net/http"

	"kingbloc.sso/user"

	"kingbloc.util/util"
	"reflect"
	"strings"
)

type PropertyObject struct {
	Id    int64  `json:'id'`
	Field string `json:"field"`
	Value string `json:"value"`
}

// 修改属性
func EditProperty(rep http.ResponseWriter, req *http.Request) {

	if strings.ToLower(req.Method) != "post" {
		rep.WriteHeader(405)
		return
	}

	var token string
	cookie, err := req.Cookie("SSOTOKEN")
	if err != nil {
		token = req.Header.Get("SSOTOKEN")
		if token == "" {
			util.WriteJSON(rep, "1")
			return
		}
	} else {
		token = cookie.Value
	}
	//
	loginUser := byToken(token)
	if loginUser == nil {
		util.WriteJSON(rep, "2")
		return
	}
	body, _ := ioutil.ReadAll(req.Body)

	//
	user := new(user.User)
	pro1 := new(PropertyObject)
	json.Unmarshal(body, &user)
	json.Unmarshal(body, &pro1)

	if pro1.Id == 0 || pro1.Field == "" || pro1.Value == "" {
		util.WriteJSON(rep, "3")
		return
	}
	if pro1.Field == "password" {
		user.Password = util.Md5EncodeForPassword(pro1.Value)
	}

	user.UpdateByCol(pro1.Field)
	rep.Write([]byte("ok"))
}

func setName(toStruct interface{}, filed string, val interface{}) {
	full := reflect.ValueOf(toStruct).Elem().FieldByName(strings.Title(filed))
	full.Set(reflect.ValueOf(val))
}

func Edit(rep http.ResponseWriter, req *http.Request) {

	var token string
	cookie, err := req.Cookie("token")
	if err != nil {
		token = req.FormValue("token")
		if token == "" {
			util.WriteJSON(rep, "1")
			return
		}
	} else {
		token = cookie.Value
	}

	//
	loginUser := byToken(token)
	if loginUser == nil {
		util.WriteJSON(rep, "2")
		return
	}

	//
	body, _ := ioutil.ReadAll(req.Body)

	userB := new(user.User)
	json.Unmarshal(body, userB)

	isOk := util.RegexpMobile.MatchString(userB.Mobile)
	if !isOk {
		util.WriteJSON(rep, "3")
		return
	}

	isOk = util.RegexpCommon.MatchString(userB.Wechat)
	if !isOk {
		util.WriteJSON(rep, "4")
		return
	}
	userB.Alias = util.RegexpFileter.ReplaceAllString(userB.Alias, "")

	if userB.Password == "" {
		util.WriteJSON(rep, "5")
		return
	}
	isOk = util.RegexpPassword.MatchString(userB.Password)
	if !isOk {
		util.WriteJSON(rep, "5")
		return
	}

	pwdRef := util.Md5EncodeForPassword(userB.Password)
	if loginUser.Password != pwdRef {
		util.WriteJSON(rep, "6")
		return
	}

	userB.Id = loginUser.Id
	userB.Update(*userB)
	util.WriteJSON(rep, "OK")
}
